<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

require_once('includes/functions/module_functions.php');
class ups
{
	var $code, $enabled;
    	function ups() 
	{
		$this->module_key = 'MODULE_SHIPPING_UPS';
		$this->code = 'ups';
		$this->enabled = ((MODULE_SHIPPING_UPS_STATUS == 'true') ? true : false);
		$this->sort_order = MODULE_SHIPPING_UPS_SORT_ORDER;

		$this->services = array(
					//'1DM',//Next Day Air Early AM
					//'1DML',//Next Day Air Early AM Letter
					//'1DA',//Next Day Air
					//'1DAL',//Next Day Air Letter
					//'1DAPI',//Next Day Air Intra (Puerto Rico)
					//'1DP',//Next Day Air Saver
					//'1DPL',//Next Day Air Saver Letter
					//'2DM',//2nd Day Air AM
					//'2DML',//2nd Day Air AM Letter
					//'2DA',//2nd Day Air
					//'2DAL',//2nd Day Air Letter
					//'3DS',//3 Day Select
					'GND',//Ground
					'GNDCOM',//Ground Commercial
					'GNDRES',//Ground Residential
					'STD',//Canada Standard
					//'XPR',//Worldwide Express
					//'XPRL',//worldwide Express Letter
					//'XDM',//Worldwide Express Plus
					//'XDML',//Worldwide Express Plus Letter
					//'XPD',//Worldwide Expedited
					);
	}

    	function quote($params, &$checkout_component)
	{
		if (!$this->enabled) return false;

		$shipping_service = $params['shipping_service'];
		if ($shipping_service == null || strlen($shipping_service) == 0 || !(in_array($shipping_service, $this->services)))
			$shipping_service = null;

		$shipping_weight = (double)$params['shipping_weight'];
		//Make sure that a weight exists.
		if ($shipping_weight == 0) $shipping_weight = .1;
		
		$shipping_num_boxes = $params['shipping_num_boxes'];
	
		$pickup = MODULE_SHIPPING_UPS_PICKUP;
		$container = MODULE_SHIPPING_UPS_PACKAGE;
		$delivery = MODULE_SHIPPING_UPS_RES;
		
		//confirm Zone
		$check_flag = check_zone(MODULE_SHIPPING_UPS_ZONE, $checkout_component->shipTo['country_id'], $checkout_component->shipTo['zone_id']);
		if ($check_flag == false) return false;

		$quotes['code'] = $this->code;
		$quotes['tax_class'] = MODULE_SHIPPING_UPS_TAX_CLASS;

		$action = 4;//All Available Quotes
		if ($shipping_service != null) $action = 3;//Single Quote


		if ($shipping_service != null && in_array($shipping_service, $this->services)) {
			$product = $shipping_service;
		} 
		else {
			$product = 'GNDRES';//dummy
		}

      		$request = join('&', array('accept_UPS_license_agreement=yes',
                                 '10_action=' . $action,
                                 '13_product=' . $product,
                                 '14_origCountry=' . $checkout_component->shipFrom['country_iso_code_2'],
                                 '15_origPostal=' . $checkout_component->shipFrom['postcode'],
                                 '19_destPostal=' . $checkout_component->shipTo['postcode'],
                                 '22_destCountry=' . $checkout_component->shipTo['country_iso_code_2'],
                                 '23_weight=' . $shipping_weight,
                                 '47_rate_chart=' . $this->upsRate($pickup),
                                 '48_container=' . $this->upsContainer($container),
                                 '49_residential=' . $this->upsRescom($delivery)));

		include_once('includes/classes/http_client.php');

		$http = new httpClient();
		if ($http->Connect('www.ups.com', 80))
		{
			$http->addHeader('Host', 'www.ups.com');
			$http->addHeader('User-Agent', 'osCommerce');
			$http->addHeader('Connection', 'Close');

			if ($http->Get('/using/services/rave/qcostcgi.cgi?' . $request)) $body = $http->getBody();

			$http->Disconnect();
		} 
		else 
		{
			$quotes['error'] = 'www.ups.com';
			return $quotes;
		}

		$body_array = explode("\n", $body);

		$rates = array();
		$errorret = 'error'; // only return error if NO rates returned

		$n = sizeof($body_array);
		for ($i=0; $i<$n; $i++) {
			$result = explode('%', $body_array[$i]);

			$errcode = substr($result[0], -1);
			switch ($errcode) {
				case 3:
					$service = $result[1];
					if (!in_array($service, $this->services)) continue;
					$rates[] = array('service' => $service, 'postage' => (double)$result[8]);
					break;
				case 4:
					$service = $result[1];
					if (!in_array($service, $this->services)) continue;
					$rates[] = array('service' => $service, 'postage' => (double)$result[8]);
					break;
				case 5:
					$errorret = $result[1];
					break;
				case 6:
					$service = $result[3];
					if (!in_array($service, $this->services)) continue;
					$rates[] = array('service' => $service, 'postage' => (double)$result[10]);
					break;
			}
		}

		if (empty($rates))
		{
			$quotes['error'] = $errorret;
			return $quotes;
		}

		//Calculate Handling
		$quotes['handling'] = MODULE_SHIPPING_UPS_HANDLING;
		$quotes['rates'] = $rates;

		return $quotes;	
	}

	function check() {
		if (!isset($this->_check)) {
			$this->_check = check_module($this->module_key);
		}
		return $this->_check;
	}

	function install() {
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Enable UPS Shipping', 'MODULE_SHIPPING_UPS_STATUS', 'true', 'Do you want to offer UPS shipping?', '6', '0','true, false', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, configuration_values) values ('UPS Pickup Method', 'MODULE_SHIPPING_UPS_PICKUP', 'CC', 'How do you give packages to UPS? CC - Customer Counter, RDP - Daily Pickup, OTP - One Time Pickup, LC - Letter Center, OCA - On Call Air', '6', '1', now(), 'CC, RDP, OTP, LC, OCA')");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, configuration_values) values ('UPS Packaging?', 'MODULE_SHIPPING_UPS_PACKAGE', 'CP', 'CP - Your Packaging, ULE - UPS Letter, UT - UPS Tube, UBE - UPS Express Box', '6', '2', now(), 'CP, ULE, UT, UBE')");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added, configuration_values) values ('Residential Delivery?', 'MODULE_SHIPPING_UPS_RES', 'RES', 'Quote for Residential (RES) or Commercial Delivery (COM)', '6', '3', now(), 'RES, COM')");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Handling Fee', 'MODULE_SHIPPING_UPS_HANDLING', '0', 'Handling fee for this shipping method.', '6', '4', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Tax Class', 'MODULE_SHIPPING_UPS_TAX_CLASS', '0', 'Use the following tax class on the shipping fee.', '6', '5', 'tax_class_list()', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Shipping Zone', 'MODULE_SHIPPING_UPS_ZONE', '0', 'If a zone is selected, only enable this shipping method for that zone.', '6', '6', 'geo_zone_list()', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_SHIPPING_UPS_SORT_ORDER', '100', 'Sort order of display. Lowest is displayed first.', '6', '7', now())");
	}

	function remove() {
		remove_module($this->module_key);
	}

	function upsRate($foo) {
		$returnCode = '';
		switch ($foo) {
			case 'RDP':
				$returnCode = 'Regular+Daily+Pickup';
				break;
			case 'OCA':
				$returnCode = 'On+Call+Air';
				break;
			case 'OTP':
				$returnCode = 'One+Time+Pickup';
				break;
			case 'LC':
				$returnCode = 'Letter+Center';
				break;
			case 'CC':
				$returnCode = 'Customer+Counter';
			break;
		}
		return $returnCode;
	}

	function upsContainer($foo) {
		$returnCode = '';
		switch ($foo) {
			case 'CP': // Customer Packaging
				$returnCode = '00';
				break;
			case 'ULE': // UPS Letter Envelope
				$returnCode = '01';
				break;
			case 'UT': // UPS Tube
				$returnCode = '03';
				break;
			case 'UEB': // UPS Express Box
				$returnCode = '21';
				break;
			case 'UW25': // UPS Worldwide 25 kilo
				$returnCode = '24';
				break;
			case 'UW10': // UPS Worldwide 10 kilo
				$returnCode = '25';
				break;
		}
		return $returnCode;
	}


	function upsRescom($foo) {
		$returnCode = '';
		switch ($foo) {
			case 'RES': // Residential Address
				$returnCode = '1';
				break;
			case 'COM': // Commercial Address
				$returnCode = '2';
				break;
		}
		return $returnCode;
	}
}
?>
